package com.jy.datapipeline.export.task;

import com.jcraft.jsch.ChannelSftp;
import com.jy.datapipeline.export.dao.ExpTaskExecuteDetailLogDao;
import com.jy.datapipeline.export.dao.ExpTaskExecuteLogDao;
import com.jy.datapipeline.export.entity.DataSourceInfoModel;
import com.jy.datapipeline.export.entity.ExpTaskExecuteLogModel;
import com.jy.datapipeline.export.dao.repo.ExpTaskExecuteDetailLogDaoRepo;
import com.jy.datapipeline.export.entity.DataStoreInfoModel;
import com.jy.datapipeline.export.entity.ExpRuleDetailModel;
import com.jy.datapipeline.export.entity.ExpRuleModel;
import com.jy.datapipeline.export.entity.ExpTaskExecuteDetailLogModel;
import com.jy.datapipeline.export.entity.ExpTaskModel;
import com.jy.datapipeline.common.util.DateUtils;
import com.jy.datapipeline.common.util.FtpUtil;
import com.jy.datapipeline.common.util.RandomNumsUtil;
import com.jy.datapipeline.common.util.TEAUtil;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Callable;
import javax.sql.DataSource;

import com.jy.datapipeline.export.service.DataDictionaryService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TaskExecuteCallable implements Callable<Boolean> {

    private int printOutSize;
    private DataSource dataSource;
    private int fetchSize;
    private String localStorePath;
    private DataSourceInfoModel dataSourceInfoModel;
    private ExpTaskExecuteLogModel expTaskExecuteLogModel;
    private ExpTaskModel expTaskModel;
    private ExpTaskExecuteDetailLogDaoRepo expTaskExecuteDetailLogDaoRepo;
    private DataStoreInfoModel dataStoreInfoModel;
    //private Connection passConnection;
    private ExpTaskExecuteDetailLogDao expTaskExecuteDetailLogDao;
    private ExpRuleModel expRuleModel;
    private ExpRuleDetailModel expRuleDetailModel = null;
    private ExpTaskExecuteDetailLogModel expTaskExecuteDetailLogModel = null;
    private String ruleTbl = "";
    private Date dataDate = null;
    private ExpTaskExecuteLogDao expTaskExecuteLogDao;
    private DataDictionaryService dataDictionaryService;

    public TaskExecuteCallable(DataSource dataSource, ExpTaskExecuteLogDao expTaskExecuteLogDao,
        ExpTaskExecuteDetailLogDao expTaskExecuteDetailLogDao,
        ExpRuleDetailModel expRuleDetailModel,
        ExpRuleModel expRuleModel,
        DataStoreInfoModel dataStoreInfoModel,
        ExpTaskExecuteDetailLogDaoRepo expTaskExecuteDetailLogDaoRepo, ExpTaskModel expTaskModel,
        ExpTaskExecuteLogModel expTaskExecuteLogModel, DataSourceInfoModel dataSourceInfoModel,
        String localStorePath, int fetchSize, int printOutSize, DataDictionaryService dataDictionaryService) {
        try {
            this.dataSource = dataSource;
            //this.passConnection=dataSource.getConnection();
            this.expTaskExecuteDetailLogDao = expTaskExecuteDetailLogDao;
            this.expRuleDetailModel = expRuleDetailModel;
            this.expRuleModel = expRuleModel;
            this.dataStoreInfoModel = dataStoreInfoModel;
            this.expTaskExecuteDetailLogDaoRepo = expTaskExecuteDetailLogDaoRepo;
            this.expTaskModel = expTaskModel;
            this.expTaskExecuteLogModel = expTaskExecuteLogModel;
            this.dataSourceInfoModel = dataSourceInfoModel;
            this.localStorePath = localStorePath;
            this.ruleTbl = expRuleDetailModel.getRuleTbl();
            this.fetchSize = fetchSize;
            this.printOutSize = printOutSize;
            this.expTaskExecuteLogDao=expTaskExecuteLogDao;
            this.dataDictionaryService = dataDictionaryService;
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public Boolean call() throws Exception {
        String selectSql = null;
        try {
            //生成查询语句
            this.dataDate = RandomNumsUtil.getDataTime(this.expRuleDetailModel.getDataUnit(),
                this.expRuleDetailModel.getDataPeriod());
            selectSql = this.createSelectSql();

            String[] colStr ={};
            if(this.expRuleDetailModel.getRuleTYpe()==3){

                colStr=RandomNumsUtil.getCollist( this.expRuleDetailModel.getRowRange()).split(",");
            }else {
                colStr=this.expRuleDetailModel.getColList().split(",");
            }
            //List<String> collist= Arrays.asList(colStr);
            //获取查询结果
            ExpTaskExecuteDetailLogModel eredlm = new ExpTaskExecuteDetailLogModel();
            String task_execute_detail_id = "t_detail_" + this.ruleTbl + "_" + System.nanoTime()
                + RandomNumsUtil.generateNumber();
            eredlm.setDataFileCount(0);
            eredlm.setTaskId(this.expTaskModel.getTaskId());
            eredlm.setDataFilePath("");
            eredlm.setDataSourceId(this.expTaskModel.getDataSourceId());
            eredlm.setExportStartTime(new Date());
            eredlm.setRuleId(this.expTaskModel.getRuleId());
            eredlm.setRuleTbl(this.ruleTbl);
            eredlm.setRuleType(this.expRuleDetailModel.getRuleTYpe());
            eredlm.setExpStatus(1);
            eredlm.setStoreId(this.expTaskModel.getStoreId());
            eredlm.setStoreType(this.dataStoreInfoModel.getStoreType());
            eredlm.setTaskExecutelogLogId(this.expTaskExecuteLogModel.getTaskExecuteLogId());
            eredlm.setUpdateTime(new Date());
            eredlm.setTaskExecuteDetailId(task_execute_detail_id);
            this.expTaskExecuteDetailLogModel = eredlm;
            this.expTaskExecuteDetailLogDaoRepo.save(this.expTaskExecuteDetailLogModel);
            this.getResult(selectSql, colStr);
        } catch (Exception e) {

            log.error("call error sql:[" + selectSql + "]", e);
        }
        return null;
    }

    private Connection getConnection() throws SQLException {
        Connection connection = this.dataSource.getConnection();
        connection.setAutoCommit(false);
        return connection;
    }

    @SneakyThrows
    public void getResult(String sql, String[] collist) {
        BufferedWriter outData = null;
        BufferedWriter outVerify = null;
        String dataFilePaths = "";
        String fileNamePre = "";
        String dataFilePath = "";
        String verifyFilePath = "";
        boolean isSftp = true;
        int line = 0;
//        int file_serize = 1;
        int totalline = 0;
        long initRow = this.expRuleDetailModel.getInitRow() == 0 ? 1000L : this.expRuleDetailModel.getInitRow() * 10000L;
        try (Connection connection = this.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
        ) {
           // connection.setAutoCommit(false);

            log.info("execute sql {} fetchSize {}", sql, fetchSize);


            preparedStatement.setFetchSize(fetchSize);
            Map<String, DataFileBean> datafileMap = new HashMap<>();

            //创建文件
            //int row=resultSet.;
            // if (resultSet.next()) {
//                Date newDate = new Date();
//
//                Calendar calendar = Calendar.getInstance();
//                calendar.setTime(newDate);
            //String nowDay = DateUtils.formatDate(dataDate, this.expRuleModel.getFileNameRule());
            String dataTime = RandomNumsUtil.getDataTimeForFileName(this.dataDate,
                this.expRuleDetailModel.getDataUnit());
            String cityCode = dataDictionaryService.findById(expTaskModel.getCityCodeId());
            fileNamePre = this.dataSourceInfoModel.getDataSourceName() + "_" +
                this.expRuleDetailModel.getSchemaName() + "_" +
                this.ruleTbl + "_"+ cityCode +"_";
            if (this.expTaskModel.getBusinessName() != null && !this.expTaskModel.getBusinessName()
                .equals("")) {
                fileNamePre = fileNamePre + this.expTaskModel.getBusinessName() + "_";
            }
            fileNamePre = fileNamePre+ dataTime;

            fileNamePre = fileNamePre.toUpperCase(Locale.ROOT);
            String folderPath = this.localStorePath;
            File folder = new File(folderPath);
            if (!folder.exists() && !folder.isDirectory()) {
                folder.mkdirs();
            }
            String dataFileName = fileNamePre + "_0001.dat";
            datafileMap.put(dataFileName, null);
            String verifyFileName = fileNamePre + ".verf";
            dataFilePath = folderPath + "/" + dataFileName;
            verifyFilePath = folderPath + "/" + verifyFileName;

            File dataFile = new File(dataFilePath);
            if (dataFile.exists()) {
                dataFile.delete();
                dataFile = new File(dataFilePath);
            }
            File verifyFile = new File(verifyFilePath);
            if (verifyFile.exists()) {
                verifyFile.delete();
                verifyFile = new File(verifyFilePath);
            }
            FileWriter dataFileWriter = new FileWriter(dataFile);
            FileWriter verifyFileWriter = new FileWriter(verifyFile);
            outData = new BufferedWriter(dataFileWriter);
            outVerify = new BufferedWriter(verifyFileWriter);
            DataFileBean dfb = new DataFileBean();
            dfb.setDataFile(dataFile);
            dfb.setFileSize(0L);
            dfb.setFileRow(0L);
            dfb.setFileName(dataFileName);
            datafileMap.put(dataFileName, dfb);
            log.info("start write resultSet ");

            StringBuilder buffWrite = new StringBuilder();
            int quotientSize = 0;
            int totalquotientSize = 0;
            boolean isSplitPage = false;
            while (resultSet.next()) {

                quotientSize = (int) (totalline / initRow);

                if (totalline >= initRow) {
                    if (quotientSize >= 1) {
                        //                       DataFileBean dfb= datafileMap.get(dataFileName);
//                        if(dfb==null){
//                            dfb= dfb==null?new DataFileBean():dfb;
//                            dfb.setFileName(dataFileName);
//                            dfb.setFileSize(dataFile.length());
//                            dfb.setFileRow((long) line);
//                            datafileMap.put(dataFileName,dfb);
//                        }
//                        else {
//                            dfb.setFileRow(line-initRow*(quotientSize));
//                            dfb.setFileSize(dfb.getDataFile().length());
//                        }

                        dataFileName = fileNamePre + "_000" + (1 + quotientSize) + ".dat";
                        dfb = datafileMap.get(dataFileName);
                        if (dfb != null) {
                            dataFile = dfb.getDataFile();
                        } else {
                            dataFilePath = folderPath + "/" + dataFileName;
                            dataFile = new File(dataFilePath);
                        }
                        if (datafileMap.get(dataFileName) == null) {
                            totalquotientSize++;
                            isSplitPage = true;

                            log.info("current split page {} ", totalquotientSize);
                            outData.flush();
                            dfb = datafileMap.get(fileNamePre + "_000" + quotientSize + ".dat");
                            dfb = dfb == null ? new DataFileBean() : dfb;
                            dfb.setFileRow((long) line);
                            dfb.setFileSize(dfb.getDataFile().length());
                            line = 0;
                            outData.close();
                            outData = null;
                            buffWrite.setLength(0);
                            if (dataFile.exists()) {
                                dataFile.delete();
                                dataFile.createNewFile();
                            }

                            dfb = new DataFileBean();
                            //
                            dfb.setFileName(dataFileName);
                            FileWriter dataFileWriter2 = new FileWriter(dataFile);
                            outData = new BufferedWriter(dataFileWriter2);
                            dfb.setDataFile(dataFile);
                            dfb.setFileRow((long) line);
                            dfb.setFileSize(dataFile.length());
                            datafileMap.put(dataFileName, dfb);
                        }

                        // if( quotientSize>=2 ){
                        //  dfb= datafileMap.get(fileNamePre+"_000"+(quotientSize-1)+".dat");
                        //  if(dfb.getFileRow()/initRow+1!=quotientSize){
                        // dfb.setFileRow(line-initRow*(quotientSize-1));
                        //  dfb.setFileSize(dfb.getDataFile().length());
                        //   }
                        //  }
//

                    }

                }
                line++;
                totalline++;
                //遍历结果
                //StringBuilder sb = new StringBuilder();
//                if(line % fetchSize==0 ){
//                    if(line!=fetchSize){
//                        outData.write("\n");
//                    }
//                    if(isSplitPage){
//                        isSplitPage=false;
//                    }
//                }
                int collength= resultSet.getMetaData().getColumnCount();
                for (int i = 0; i < collength; i++) {
                    Object value = resultSet.getObject(i + 1);
                    if (value instanceof Timestamp) {
                        Timestamp ts = (Timestamp) value;
                        // buffWrite.append( DateUtils.formatDate(new Date(ts.getTime()),"yyyy-MM-dd HH:mm:ss"));
                        outData.write(
                            DateUtils.formatDate(new Date(ts.getTime()), "yyyy-MM-dd HH:mm:ss"));
                    } else if (value instanceof java.sql.Date) {
                        java.sql.Date date2 = (java.sql.Date) value;
                        //buffWrite.append( DateUtils.formatDate(date2,"yyyy-MM-dd HH:mm:ss"));
                        outData.write(DateUtils.formatDate(date2, "yyyy-MM-dd HH:mm:ss"));
                    } else if(value instanceof Clob){
                        Clob clob = (Clob) value;
                        outData.write(clobToString(clob));
                    }
                    else if(value instanceof Blob){
                        Blob blob = (Blob) value;
                        outData.write(blobToString(blob));
                    }
                    else if(value instanceof SQLXML){
                        SQLXML sqlxml = (SQLXML) value;
                        outData.write(xmlToString(sqlxml));
                    }else if (value != null) {
                        String valueStr = String.valueOf(value);
                        //if(valueStr.indexOf("\\n")>-1){
                        // buffWrite.append(valueStr.replaceAll("\\n|\\r",""));
                        outData.write(valueStr.replace("\n", "").replace("\r", ""));
//                        }else{
                        //   buffWrite.append(value);
//                        }

                    }
                    if (i + 1 < collist.length) {
                        //buffWrite.append(this.expRuleModel.getColSeparator());
                        outData.write(this.expRuleModel.getColSeparator());
                    }
                }
                // buffWrite.append("\n");
                outData.write("\n");
                if (totalline % printOutSize == 0) {
                    log.info(" table [" + this.ruleTbl + "] logId ["
                        + this.expTaskExecuteDetailLogModel.getTaskExecuteDetailId()
                        + "] current line [" + totalline + "]");
                }

                if (line % fetchSize == 0) {
                    //buffWrite.deleteCharAt(buffWrite.length()-1);
                    //outData.write(buffWrite.toString());
                    // buffWrite.setLength(0);
                    outData.flush();
                }
            }

            if (buffWrite.length() > 0) {
//                if(line!=fetchSize && !isSplitPage){
//                    outData.write("\n");
//                }
                //buffWrite.deleteCharAt(buffWrite.length()-1);
                outData.write(buffWrite.toString());
            }
            outData.flush();
            dfb = datafileMap.get(dataFileName);
            dfb = dfb == null ? new DataFileBean() : dfb;
            dfb.setFileName(dataFileName);
            dfb.setFileSize(dataFile.length());
            dfb.setFileRow((long) line);
            datafileMap.put(dataFileName, dfb);

            log.info(" table [" + this.ruleTbl + "] export end total [" + totalline + "] ");

            StringBuilder verifySb = new StringBuilder();
            for (int i = 0; i <= totalquotientSize; i++) {
                String key = fileNamePre + "_000" + (i + 1) + ".dat";
                DataFileBean dfb2 = datafileMap.get(key);
                // dfb2.getFileName();
                dataFilePaths += folderPath + "/" + dfb2.getFileName();
                verifySb.append(
                    dfb2.getFileName() + "|" + dfb2.getFileSize() + "|" + dfb2.getFileRow());
                verifySb.append("\n");
                if (i + 1 <= totalquotientSize) {
                    dataFilePaths += ",";
                }

            }
            datafileMap.keySet().forEach(key -> {
                datafileMap.get(key).getFileName();

            });

            outVerify.write(verifySb.toString());
            outVerify.flush();
//            connection.commit();


        } catch (IOException e) {
//            connection.rollback();
            log.error("getResult IOException error", e);
            this.expTaskExecuteDetailLogModel.setExpStatus(-1);//导出异常
            this.expTaskExecuteDetailLogModel.setSftpeEndtime(new Date());
            this.expTaskExecuteDetailLogModel.setErrorMsg(
                "{sql:" + sql + ",error_msg:" + e.getMessage() + "}");
            this.expTaskExecuteDetailLogDao.updateExpStatus(this.expTaskExecuteDetailLogModel);
            isSftp = false;
        } catch (SQLException e) {
//            connection.rollback();
            log.error("getResult SQLException error", e);
            this.expTaskExecuteDetailLogModel.setExpStatus(-1);//导出异常
            this.expTaskExecuteDetailLogModel.setSftpeEndtime(new Date());
            this.expTaskExecuteDetailLogModel.setErrorMsg(
                "{sql:" + sql + ",error_msg:" + e.getMessage() + "}");
            this.expTaskExecuteDetailLogDao.updateExpStatus(this.expTaskExecuteDetailLogModel);
            isSftp = false;

            this.expTaskExecuteLogDao.updateExeuceStatus(this.expTaskExecuteDetailLogModel.getTaskExecutelogLogId(),3,totalline,verifyFilePath,e.getMessage());

        } finally {
//            connection.close();
            if (outData != null) {
                outData.close();
            }
            if (outVerify != null) {
                outVerify.close();
            }
        }
        if (isSftp) {
            this.expTaskExecuteDetailLogModel.setDataFileNamePrefix(fileNamePre);

            this.expTaskExecuteDetailLogModel.setDataFilePath(dataFilePaths);
            this.expTaskExecuteDetailLogModel.setExpStatus(2);//导出完成
            this.expTaskExecuteDetailLogModel.setExportEndTime(new Date());
            this.expTaskExecuteDetailLogModel.setDataFileCount(totalline);
            this.expTaskExecuteDetailLogDao.updateExpStatus(this.expTaskExecuteDetailLogModel);
            //开始上传
            String[] datafilePathArr = dataFilePaths.split(",");
            this.expTaskExecuteDetailLogModel.setExpStatus(3);//上传中
            this.expTaskExecuteDetailLogModel.setSftpStartTime(new Date());
            this.expTaskExecuteDetailLogDao.updateExpStatus(this.expTaskExecuteDetailLogModel);

            if (datafilePathArr.length > 0) {
                for (int i = 0; i < datafilePathArr.length; i++) {
                    this.uploadBySftp(datafilePathArr[i]);
                }
            }
            this.uploadBySftp(verifyFilePath);

            this.expTaskExecuteDetailLogModel.setExpStatus(4);//上传完成
            this.expTaskExecuteDetailLogModel.setSftpeEndtime(new Date());
            this.expTaskExecuteDetailLogDao.updateExpStatus(this.expTaskExecuteDetailLogModel);
            this.expTaskExecuteLogDao.updateExeuceStatus(this.expTaskExecuteDetailLogModel.getTaskExecutelogLogId(),4,totalline,verifyFilePath,"");

        }
        //将结果写入到文件中
        //this.createFile(contextList);

    }


    public void uploadBySftp(String file) {
        ChannelSftp channelSftp = null;
        try {
            log.info("start sftp connection");
            channelSftp = FtpUtil.connectBySftp(this.dataStoreInfoModel.getHost(),
                this.dataStoreInfoModel.getUserName(),
                TEAUtil.decode(this.dataStoreInfoModel.getPassword()));
            log.info("end sftp connection");

            FtpUtil.uploadFileBySftp(file, this.dataStoreInfoModel.getRemotePath(),
                channelSftp, this.expRuleModel.getIsFile());
            FtpUtil.disconnect(channelSftp);

        } catch (Exception e) {
            log.error("uploadBySftp error ", e);
            this.expTaskExecuteDetailLogModel.setErrorMsg(e.getMessage());
            this.expTaskExecuteDetailLogModel.setExpStatus(-3);//上传异常
            this.expTaskExecuteDetailLogModel.setSftpeEndtime(new Date());
            this.expTaskExecuteDetailLogDao.updateExpStatus(this.expTaskExecuteDetailLogModel);
            FtpUtil.disconnect(channelSftp);
        }


    }

    public String createSelectSql() {
        StringBuilder sb = new StringBuilder();
        if (this.expRuleDetailModel.getRuleTYpe() == 3) {
            sb.setLength(0);
            sb.append(
                RandomNumsUtil.paramsToStr(this.expRuleDetailModel.getRowRange(), this.dataDate));
            if (this.expRuleDetailModel.getRuleTblType() == 1) {
                this.ruleTbl = RandomNumsUtil.getTable(this.dataDate,
                    this.expRuleDetailModel.getRuleTblSuffix(), this.ruleTbl,
                    this.expRuleDetailModel.getFunValue());
            }
        }else {
            sb.append(" SELECT ");
            sb.append(this.expRuleDetailModel.getColList());
            if (this.expRuleDetailModel.getRuleTblType() == 0) {
                sb.append(" FROM " + this.expRuleDetailModel.getSchemaName() + "." + this.ruleTbl);
            }else{

                this.ruleTbl = RandomNumsUtil.getTable(this.dataDate,
                    this.expRuleDetailModel.getRuleTblSuffix(), this.ruleTbl,this.expRuleDetailModel.getFunValue());
                sb.append(" FROM " + this.expRuleDetailModel.getSchemaName() + "." + this.ruleTbl);
            }

            if (this.expRuleDetailModel.getRuleTYpe() == 2) {

//            JSONArray jsonArray = JSONArray.parseArray(this.expRuleDetailModel.getRowRange());
//            if (!jsonArray.isEmpty()) {
                sb.append(" WHERE ");
//                for (int i = 0; i < jsonArray.size(); i++) {
//                    JSONObject jsonObject = jsonArray.getJSONObject(i);
//                    String column = jsonObject.getString("column");
//                    String compare = jsonObject.getString("compare");
//                    String value = jsonObject.getString("value");
//                    String column_type = jsonObject.getString("column_type")
//                        .toLowerCase(Locale.ROOT);
//                    sb.append(column + " " + compare);
//                    if (column_type != null && (column_type.indexOf("varchar") > -1
//                        || column_type.indexOf("char") > -1 ||
//                        column_type.indexOf("blob") > -1 ||
//                        column_type.indexOf("clob") > -1)) {
//                        sb.append("'" + value + "'");
//                    } else if (column_type != null && column_type.indexOf("timestamp") > -1) {
//                        if (value.indexOf("#") > -1) {
//                            sb.append("  " + RandomNumsUtil.paramsToStr(value));
//                        } else {
//                            sb.append(" to_timestamp('" + value + "','YYYY-MM-DD HH24:MI:SS')");
//                        }
//                    } else if (column_type != null && column_type.indexOf("date") > -1) {
//                        if (value.indexOf("#") > -1) {
//                            sb.append("  " + RandomNumsUtil.paramsToStr(value));
//                        } else {
//                            sb.append(" to_date('" + value + "','YYYY-MM-DD HH24:MI:SS')");
//                        }
//                    } else {
//                        sb.append("'" + value + "'");
//                    }
//                    if (i + 1 < jsonArray.size()) {
//                        sb.append(" and ");
//                    }
//                }
//            }

//            if (this.expRuleDetailModel.getRowRange().indexOf("'#system.YYYYMM#'")>-1 ||
//                this.expRuleDetailModel.getRowRange().indexOf("'#system.YYYYMMDD#'")>-1
//            ){

                sb.append(
                    RandomNumsUtil.paramsToStr(this.expRuleDetailModel.getRowRange(),
                        this.dataDate));
                // }
            }
        }
        return sb.toString();
    }

    private static String clobToString(Clob clob) throws SQLException, IOException {
        StringBuilder sb = new StringBuilder();
        try (Reader reader = clob.getCharacterStream()) {
            char[] buffer = new char[1024];
            int bytesRead;
            while ((bytesRead = reader.read(buffer)) != -1) {
                sb.append(buffer, 0, bytesRead);
            }
        }
        return sb.toString();
    }

    private static String blobToString(Blob blob) throws SQLException, IOException {
        byte[] bytes = blob.getBytes(1, (int) blob.length());
        return new String(bytes);
    }

    private static String xmlToString(SQLXML xml) throws SQLException {
        return xml.getString();
    }

//    public static void main(String[] args) {
//
//        Long nowTime=System.nanoTime();
//       // System.out.println("start"+str);
//        for(int i=0;i<10000;i++){
//            String str="start===>sdsdsdsss\nmsdsdsdsd\r,sdsdsds\n,dsdsds\rsdsdsdasdadsadssa <=====end";
//
//
//            str=str.replaceAll("\n","").replaceAll("\r","");
//           // str=str.replace("\n","") .replace("\r","");
//           // str=str.replace("\r","");
//
//           // System.out.println(str);
//        }
//        Long endTime=System.nanoTime();
//        System.out.println("use time "+(endTime-nowTime)/1000000);
//    }
}
